package com.gx.config;

import com.gx.common.JwtTokenEnhancer;
import com.gx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * 认证服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private static final String CLIEN_ID_ONE = "admin";  //客户端1 用来标识客户的Id
    private static final String CLIEN_ID_TWO = "client_2";  //客户端2
    private static final String CLIENT_SECRET = "admin123456";   //secret客户端安全码
    private static final String GRANT_TYPE_PASSWORD = "password";   // 密码模式授权模式
    private static final String AUTHORIZATION_CODE = "authorization_code"; //授权码模式  授权码模式使用到了回调地址，是最为复杂的方式，通常网站中经常出现的微博，qq第三方登录，都会采用这个形式。
    private static final String REFRESH_TOKEN = "refresh_token";  //
    private static final String IMPLICIT = "implicit"; //简化授权模式
    private static final String GRANT_TYPE = "client_credentials";  //客户端模式
    private static final String SCOPE_READ = "read";
    private static final String SCOPE_WRITE = "write";
    private static final String SCOPE_ALL = "all";
    private static final String TRUST = "trust";
    private static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1 * 60 * 60;
    private static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6 * 60 * 60;
    private static final String RESOURCE_ID = "*";    //指定哪些资源是需要授权验证的

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    //@Qualifier("redisTokenStore")
    @Qualifier("jwtTokenStore")
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;

    /**
     * 使用密码模式需要配置
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer); //配置JWT的内容增强器
        delegates.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(delegates);

        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userService)
                .tokenStore(tokenStore)//配置令牌存储策略
                .accessTokenConverter(jwtAccessTokenConverter)
                .tokenEnhancer(enhancerChain);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        String secret = passwordEncoder.encode(CLIENT_SECRET);
        //        String secret = new BCryptPasswordEncoder().encode(CLIENT_SECRET);  // 用 BCrypt 对密码编码，需要改service处密码加密

        clients.inMemory()
                .withClient(CLIEN_ID_ONE)//配置client_id
//                .resourceIds(RESOURCE_ID)
                .secret(secret)//配置client_secret
                .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)//配置访问token的有效期
                .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS)//配置刷新token的有效期
                .redirectUris("http://www.baidu.com")//单点登录时配置,配置redirect_uri，用于授权成功后跳转
//                .redirectUris("http://localhost:9401/login") //单点登录时配置
                .scopes(SCOPE_ALL)//配置申请的权限范围
                .autoApprove(true) //自动授权配置
                .authorizedGrantTypes(AUTHORIZATION_CODE, GRANT_TYPE_PASSWORD, REFRESH_TOKEN)//配置grant_type，表示授权类型
                .and()

                .withClient(CLIEN_ID_TWO)//配置client_id
//                .resourceIds(RESOURCE_ID)
                .secret(secret)//配置client_secret
                .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)//配置访问token的有效期
                .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS)//配置刷新token的有效期
                .redirectUris("http://www.baidu.com")//单点登录时配置,配置redirect_uri，用于授权成功后跳转
//                .redirectUris("http://localhost:9401/login") //单点登录时配置
                .scopes(SCOPE_ALL)//配置申请的权限范围
                .autoApprove(true) //自动授权配置
                .authorizedGrantTypes(AUTHORIZATION_CODE, GRANT_TYPE_PASSWORD, REFRESH_TOKEN);//配置grant_type，表示授权类型
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.tokenKeyAccess("isAuthenticated()"); // 获取密钥需要身份认证，使用单点登录时必须配置
    }

}
